package ru.ifmo.rybakov.muclumon.utils;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.joda.time.Seconds;

import ru.ifmo.rybakov.muclumon.Database;
import ru.ifmo.rybakov.muclumon.DateTimeValue;
import ru.ifmo.rybakov.muclumon.NumericValue;
import ru.ifmo.rybakov.muclumon.Properties;
import ru.ifmo.rybakov.muclumon.PropertyManager;
import ru.ifmo.rybakov.muclumon.StringValue;
import ru.ifmo.rybakov.muclumon.Task;

public class SEMPStatisticsWriter {

	/**
	 * @param args
	 */
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		EntityManager em = Database.getEntityManagerFactory().createEntityManager();
		try {
			Query query = em.createQuery("SELECT t FROM Task t");
			List<Task> tasks = query.getResultList();
			System.out.println("ID\tshift\tpre-n\ttime");
			for (Task task : tasks) {
				StringValue appValue = (StringValue) task.getSingleValue(PropertyManager.get(Properties.TASK_APPLICATION));
				StringValue resultValue = (StringValue) task.getSingleValue(PropertyManager.get(Properties.TASK_RESULT));
				NumericValue basisFunctionsValue = (NumericValue) task.getSingleValue(PropertyManager.get(Properties.BASIS_FUNCTIONS));
				if (resultValue == null || appValue == null || basisFunctionsValue == null) {
					continue;
				}
				String result = resultValue.getValue().toString();
				String app = appValue.getValue().toString();
				double bf = basisFunctionsValue.getValue();
				if (!"COMPLETED".equals(result) || !"SEMP".equals(app) || !(bf == 325)) {
					continue;
				}
				NumericValue shiftValue = (NumericValue) task.getSingleValue(PropertyManager.get(Properties.SEMP_SHIFT_LAYERS));
				// NumericValue dumpingValue = (NumericValue) task.getSingleValue(PropertyManager.get(Properties.SEMP_DUMPING));
				NumericValue precisionValue = (NumericValue) task.getSingleValue(PropertyManager.get(Properties.SEMP_PRECISION));
				DateTimeValue startedValue = (DateTimeValue) task.getSingleValue(PropertyManager.get(Properties.TASK_STARTED));
				DateTimeValue finishedValue = (DateTimeValue) task.getSingleValue(PropertyManager.get(Properties.TASK_FINISHED));
				if (startedValue != null && finishedValue != null && shiftValue != null && precisionValue != null) {
					 int y = Seconds.secondsBetween(startedValue.getValue(), finishedValue.getValue()).getSeconds();
					 System.out.println(task.getForeignId() + "\t" + shiftValue.getValue() + "\t" + precisionValue.getValue() + "\t" + y);
				}
			}
		} finally {
			em.close();
		}
	}

}
